using System;

namespace Extensions.RateLimiter.Counter
{
    /// <summary>
    /// 计数器限流策略
    /// </summary>
    public class CounterThrottleStrategy
    {
        /// <summary>
        /// 限制数量
        /// </summary>
        private readonly long _limitCount;

        /// <summary>
        /// 间隔秒数
        /// </summary>
        private readonly int _intervalSeconds;

        /// <summary>
        /// 已使用数量
        /// </summary>
        private long _usedCount;

        /// <summary>
        /// 开始计数时间
        /// </summary>
        private DateTime _beginTime;

        public CounterThrottleStrategy(long limitCount, int intervalSeconds)
        {
            _limitCount = limitCount;
            _intervalSeconds = intervalSeconds;
            _beginTime = DateTime.Now;
        }

        public bool IsLimit(int n = 1)
        {
            var nowTime = DateTime.Now;
            if (nowTime >= this._beginTime.AddSeconds(this._intervalSeconds))
            {
                this._beginTime = nowTime;
                this._usedCount = 0;
            }

            this._usedCount += n;

            return this._limitCount >= this._usedCount;
        }
    }
}